const grids = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
]

function updateDom() {
    for (let row = 0; row < grids.length; row++) {
        for (let col = 0; col < grids[row].length; col++) {
            const index = 3 * row + col
            const value = grids[row][col]
            document.getElementsByClassName('img_wrap')[index].setAttribute("value", value)
        }
    }
}

function isOk() {
    for (let row = 0; row < grids.length; row++) {
        for (let col = 0; col < grids[row].length; col++) {
            const index = 3 * row + col
            const value = grids[row][col]
            if (index !== value) return false
        }
    }
    return true;
}

function findIndex(value) {
    value = +value
    for (let row = 0; row < grids.length; row++) {
        for (let col = 0; col < grids[row].length; col++) {
            if (value === grids[row][col]) {
                return [row, col]
            }
        }
    }
    return [-1, -1]
}
function move(row1, col1, row2, col2) {
    const temp = grids[row1][col1]
    grids[row1][col1] = grids[row2][col2]
    grids[row2][col2] = temp
}

// 打乱顺序
function shuffle() {
    // 不是随便打乱，而是将8按照可以移动的规则进行移动，随机移动1000步，算作打乱
    let times = 1000
    for (let i = 0; i < times; i++) {
        const [row, col] = findIndex(8)
        // 移动方向分成上下左右四个方向，随机出现
        const [rowAdd, colAdd] = [[0, 1], [0, -1], [1, 0], [-1, 0]][Math.floor(Math.random() * 4)]
        const [rowTo, colTo] = [row + rowAdd, col + colAdd]
        if (rowTo >= 0 && rowTo <= 2 && colTo >= 0 && colTo <= 2) {
            move(row, col, rowTo, colTo)
        }
    }
    // 统一更新dom结构
    updateDom()
}

function handleClick(event) {
    const element = event.target
    const value = element.getAttribute('value')
    // 查询所在位置
    const [row, col] = findIndex(value)
    // 判断能否移动(查询8所在的位置，判断当前位置与8所在的位置相连接)
    const [row8, col8] = findIndex(8)

    console.log(row, col, row8, col8)
    if (Math.abs(row - row8) + Math.abs(col - col8) === 1) {
        // 移动
        console.log('move')
        move(row, col, row8, col8)
        updateDom()
        if (isOk()) {
            setTimeout(() => {
                alert('成功')
            }, 10);
        }
        // 判断是否结束

    }


}

function handleRestart() {
    shuffle()
}
// shuffle()